

import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pleasure_video/test/webview_html_data.dart';
import 'package:webview_flutter/platform_interface.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_pleasure_video/util/extensions/string_extensions.dart';

class FeedWebViewPage extends StatefulWidget {
  @override
  _FeedWebViewPageState createState() => _FeedWebViewPageState();
}

class _FeedWebViewPageState extends State<FeedWebViewPage> {

  WebViewController? _webViewController;

  @override
  void initState() {
    super.initState();
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: WebView(
        javascriptMode: JavascriptMode.unrestricted,
        onPageStarted: pageStartedCallback,
        onPageFinished: pageFinishedCallback,
        onWebResourceError: webResourceErrorCallback,
        onWebViewCreated:webViewCreatedCallback,
        javascriptChannels: [_toastJsChannel(context)].toSet(),
        initialUrl: Uri.dataFromString(html_str,
            mimeType: 'text/html',
            encoding: Encoding.getByName('utf-8'))
            .toString(),
      ),
    );
  }
  // 创建 JavascriptChannel
  JavascriptChannel _toastJsChannel(BuildContext context) => JavascriptChannel(
      name: 'Print',
      onMessageReceived: (JavascriptMessage message) {
        "get message from JS, message is: ${message.message}".print;
        "message.message:${message.message}".print;
      });

  pageStartedCallback(String url){
    print("pageStartedCallback,url:$url");
  }

  pageFinishedCallback(String url){
    print("pageFinishedCallback,url:$url");

  }

  webResourceErrorCallback(WebResourceError error){
    print("error:${error.toString()}");
  }


  webViewCreatedCallback(WebViewController controller)async{
    this._webViewController=controller;
    print("webview page: webview created...");
    _webViewController!.loadUrl(new Uri.dataFromString(html_str,
        mimeType: 'text/html',
        encoding: Encoding.getByName('utf-8'))
        .toString());
  }

}
